package com.fangyahao.role.controller;

import com.fangyahao.role.base.BaseController;
import com.fangyahao.role.bean.RoleBean;
import com.fangyahao.role.service.RoleService;
import com.fangyahao.role.service.impl.RoleServiceImpl;
import com.fangyahao.role.utils.HttpRequestPost;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@WebServlet(name = "fangyahaoRoleController",urlPatterns = "/fangyahao/role")
public class RoleController extends BaseController {

    private RoleService service = new RoleServiceImpl();





    public void doGet(ServletRequest request,ServletResponse response){
        String flag = request.getParameter("flag");
        if("all".equals(flag)){


            List<RoleBean> allRole = service.findAllRole();
            printData(true,allRole,200,response);

        }
    }

    public void doPost(ServletRequest request,ServletResponse response) throws IOException {
        Map postMessage = HttpRequestPost.stringToMap(request);

        String flag = (String) postMessage.get("flag");
        if("insert".equals(flag)){




            String name = (String) postMessage.get("name");

            service.insertRole(name);


        }else if("delete".equals(flag)){


            Object get=postMessage.get("id");
            Integer id =null;
            if(get instanceof Integer){
                id = (Integer) get;
            }else {
                String str = (String)get;
                id=Integer.parseInt(str);
            }

            int rs = service.deleteRoleById(id);
            printData(true,rs,200,response);



        }else if("update".equals(flag)){



            String name = (String) postMessage.get("name");
            String newName = (String) postMessage.get("newName");
            service.updateRoleNameByName(name,newName);

        }


    }

    @Override
    public void service(ServletRequest servletRequest, ServletResponse response) throws ServletException, IOException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;

        HttpSession session = request.getSession();
        Integer userId =(Integer) session.getAttribute("userId");


        if(userId!=null&&service.isHavePermissions(userId)){
            String method = request.getMethod();

            if(GET_METHOD.equals(method)){
                doGet(request,response);
            }else if(POST_METHOD.equals(method)){
                doPost(request,response);
            }
        }else if(!service.isHavePermissions(userId)){
            printData(false,null,404,response);
        }



    }
}
